package com.yike.base.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yike.base.entity.Area;
import com.yike.base.entity.Company;
import com.yike.base.mapper.AreaMapper;
import com.yike.base.mapper.CompanyMapper;
import com.yike.base.service.AreaService;
import com.yike.base.vo.AreaTreeVo;
import com.yike.base.vo.AreaVo;
import com.yike.common.api.ApiResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *  控制器
 *
 * @author Sakura
 * @since 2024-08-12
 */
@Slf4j
@RestController
@RequestMapping("/area")
@Api(value = "区域管理API", tags = {"区域管理"})
public class AreaController {

    @Autowired
    private AreaService areaService;

    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private CompanyMapper companyMapper;

    @ApiOperation(value = "获取子区域列表", response = AreaVo.class)
    @GetMapping("getSubAreas/{parentId}")
    public ApiResult<List<AreaVo>> getSubAreas(@PathVariable Integer parentId) {
        List<AreaVo> areaVos = areaService.getSubAreas(parentId);
        return ApiResult.ok(areaVos);
    }

    @ApiOperation(value = "获取所有的区域", response = AreaTreeVo.class)
    @GetMapping("getAreas")
    public ApiResult<List<AreaTreeVo>> getAreas() throws Exception {
        List<AreaTreeVo> areaVos = areaService.getAreas();
        return ApiResult.ok(areaVos);
    }


    @GetMapping("ceshi")
    public void ceshi() throws Exception {
        // 1. 获取公司信息
        List<Company> companies = companyMapper.selectList(null);
        // 2. 定义正则表达式匹配括号内的内容
        Pattern bracketPattern = Pattern.compile("（(.*?)）");
        // 3. 常见的行政区划后缀
        String[] suffixes = {"省", "市", "区", "县", "自治州", "自治县"};
        for (Company company : companies) {
            String companyName = company.getName();
            String areaName = null;
            // 4. 提取括号内的内容
            Matcher matcher = bracketPattern.matcher(companyName);
            if (matcher.find()) {
                areaName = matcher.group(1); // 提取括号内内容
                // 去掉行政区划后缀
                for (String suffix : suffixes) {
                    if (areaName.endsWith(suffix)) {
                        areaName = areaName.substring(0, areaName.length() - suffix.length());
                        break; // 匹配一个后缀后立即退出
                    }
                }
            }
            // 5. 如果没有括号内的地区，则取公司名称前两位
            if (areaName == null || areaName.isEmpty()) {
                areaName = companyName.substring(0, Math.min(2, companyName.length()));
            }
            // 6. 根据提取的地区信息去匹配 Area 表
            Area area = areaMapper.selectOne(Wrappers.lambdaQuery(
                    Area.class).like(Area::getName, areaName).last("limit 1"));
            if (area != null) {
                String areaName1 = area.getName() + area.getExtra() + area.getSuffix();
                // 判断是否存在上级地区
                if (area.getParentId() != null && area.getParentId() != 0) {
                    Area parentArea = areaMapper.selectById(area.getParentId());
                    if (parentArea != null) {
                        areaName1 = parentArea.getName() + parentArea.getExtra() + parentArea.getSuffix() + areaName1;
                        if (parentArea.getParentId() != null && parentArea.getParentId() != 0) {
                            Area grandParentArea = areaMapper.selectById(parentArea.getParentId());
                            if (grandParentArea != null) {
                                areaName1 = grandParentArea.getName() + grandParentArea.getExtra() + grandParentArea.getSuffix() + areaName1;
                            }
                        }
                    }
                }
                company.setAreaName(areaName1);
                companyMapper.updateById(company);
            } else {
                log.info("未匹配到任何地区: " + companyName);
                // TODO: 记录未匹配的公司，方便后续处理
            }
        }
    }

}

